//总页数
let allPage = 1;
let allPageOther = 1;
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');
let medicalId;
let prescriptionId;
let institutionId;
$(document).ready(function () {
    loadNotReviewedItem();
    loadReviewedItem();
    $(".my_date_control").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式
        yearSuffix: '年', //年的后缀
        showMonthAfterYear: true,//是否把月放在年的后面
        maxDate: (function () {
            return todayTxt;
        })(),//最大日期
        yearRange: (function () {
            // '1990:2010'
            let year1 = '1900';
            let year2 = today.getFullYear();
            return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
        dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
        onUpdatedDatepicker: function (_year, _month, _calendar) {
            let $c = $('div#ui-datepicker-div');
            $c.find('td[data-handler="selectDay"]').each(function (idx, d) {
                let $d = $(d);
                $d.css({'pointer-events': 'auto', 'opacity': 1});
            });
        }
    });


    //切换违规记录和医疗机构
    $(".notReviewedTabDiv").on('click', function (e) {
        $("#notReviewedDiv").show();
        $("#pageDiv").show();
        $("#reviewedDiv").hide();
        $("#pageDivOther").hide();
        $(".notReviewedTabDiv").css({"background": "#1D558E", "border": "1px solid #1D558E", "color": "#FFFFFF"})
        $(".reviewedTabDiv").css({"background": "#FFFFFF", "border": "1px solid #707070", "color": "#585858"})
    });

    $(".reviewedTabDiv").on('click', function (e) {
        $("#reviewedDiv").show();
        $("#pageDivOther").show();
        $("#notReviewedDiv").hide();
        $("#pageDiv").hide();
        $(".reviewedTabDiv").css({"background": "#1D558E", "border": "1px solid #1D558E", "color": "#FFFFFF"})
        $(".notReviewedTabDiv").css({"background": "#FFFFFF", "border": "1px solid #707070", "color": "#585858"})
    });

    $('input[type=radio][name=resultRadio]').change(function () {
        if (this.value == '1') {//合规
            $("#msgIdDiv").hide();
            $("#msgContextDiv").hide();
            $("#msgDateDiv").hide();
        } else if (this.value == '2') {
            $("#msgIdDiv").show();
            $("#msgContextDiv").show();
            $("#msgDateDiv").show();
        }
    });

});

$('#notReviewedSearch').on('click', function () {
    loadNotReviewedItem();
});


$('#reviewedSearch').on('click', function () {
    loadReviewedItem();
});


$('#saveLink').on('click', function () {

    let msgTxt = $("#violationContext").val();
    let violateDt = $("#violateDt").val();

    let auditResult = $(':radio[name="resultRadio"]:checked').val();
    if (!auditResult) {
        WeKnow.errorMsg('请选择审核结果');
        return false;
    }

    var chk_value = [];//定义一个数组
    $('input[name="violationCheckbox"]:checked').each(function () {//遍历每一个名字为interest的复选框，其中选中的执行函数
        chk_value.push($(this).val());//将选中的值添加到数组chk_value中
    });
    if (auditResult == 2) {
        if (!chk_value.length) {
            WeKnow.errorMsg('请勾选违规类目');
            return false;
        }

        if (!msgTxt) {
            WeKnow.errorMsg('请填写违规内容');
            return false;
        }
        if (!violateDt) {
            WeKnow.errorMsg('请填写开具处方日期');
            return false;
        }
    }
    var data = {};
    data.medicalId = medicalId;
    data.prescriptionId = prescriptionId;
    data.institutionId = institutionId;
    data.auditResult = auditResult;
    data.msgTxt = msgTxt;
    data.msgIds = chk_value;
    data.violateDt = violateDt;
    if (auditResult == 1) {
        data.msgTxt = null;
        data.msgIds = null;
        data.violateDt = null;
    }
    WeKnow.loading();
    $.ajax({
        type: "POST",
        url: "prescriptionAudit/auditPrescription",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(data),
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
            if (data.errcode == 0) {
                WeKnow.successMsg("审核成功");
                window.location.reload();
            } else if (data.errcode == -1) {
                WeKnow.errorMsg(data.errMsg);
            } else {
                WeKnow.systemMsg('查询失败，请重新登录后再试');
            }
        }
    });


});


function loadNotReviewedItem() {

    var params = getNotReviewedParams();
    if (params) {
        var $tbody = $('#tbodyNotReviewedTableList');
        $tbody.empty();
        WeKnow.loading();
        $.ajax({
            type: "POST",
            url: "prescriptionAudit/notReviewedList",
            dataType: "json",
            data: params,
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if (data.errcode == 0) {
                    let dataInfo = data.notReviewedList;
                    if (dataInfo && dataInfo.length) {
                        let e = '';
                        $(dataInfo).each(function (idx, rowData) {
                            e += '<tr  data-reviewed_id="' + rowData.id + '" data-prescription_pic_url="' + rowData.prescriptionPicUrl + '" data-institution_id="' + rowData.institutionId + '" data-medical_id="' + rowData.medicalId + '" data-prescription_id="' + rowData.prescriptionId + '"   >';
                            // 序号
                            e += '<td class="text-center">' + (idx + 1) + '</td>';
                            // 上传日期
                            e += '<td class="text-center">' + (rowData.uploadTmStr ? rowData.uploadTmStr : "-") + '</td>';
                            // 医疗机构
                            e += '<td class="text-center">' + (rowData.name ? rowData.name : "-") + '</td>';
                            //上传人员
                            e += '<td class="text-center">' + (rowData.uploaderName ? rowData.uploaderName : "-") + '</td>';
                            // 操作
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="showImgSpan">查看处方</span></a>';
                            e += '<a href="#"><span class="showAuditImgSpan">审核</span></a>';
                            e += '<a href="#"><span class="deleteSpan">删除</span></a>';
                            e += '</td>';
                            e += '</tr>';
                        });
                        $tbody.append(e);
                    } else {
                        WeKnow.notifyMsg('暂无数据');
                    }
                    //页码修改
                    if (allPage != data.pages) {
                        allPage = data.pages;
                        //重新生成页面下拉
                        let $selectPage = $('#selectPage');
                        $selectPage.empty();
                        let e = '';
                        for (let i = 1; i <= allPage; i++) {
                            e += '<option value="' + i + '">' + i + '</option>';
                        }
                        $selectPage.append(e);
                        //总页码
                        $(".allPage").html("共" + allPage + "页");
                    }
                    //限制上一页
                    if (params.pageNum == 1) {
                        $(".upPageDiv").html('上一页');
                    } else {
                        $(".upPageDiv").html('<a href="javascript:updatePage(' + (parseInt(params.pageNum) - 1) + ')">上一页</a>');
                    }
                    //限制下一页
                    if (params.pageNum >= allPage) {
                        $(".downPageDiv").html('下一页');
                    } else {
                        $(".downPageDiv").html('<a href="javascript:updatePage(' + (parseInt(params.pageNum) + 1) + ')">下一页</a>');
                    }
                    //修改当前页码
                    $("#selectPage").val(params.pageNum);
                } else if (data.errcode == -1) {
                    WeKnow.errorMsg(data.errMsg);
                } else {
                    WeKnow.systemMsg('查询失败，请重新登录后再试');
                }
            }
        });
    }
}

//页面变更
$("#selectPage").on('change', function (e) {
    updatePage($(this).val())
});
//limit变更
$("#pageSize").on('change', function (e) {
    //重置页码
    $("#pageNum").val(1);
    //查询数据
    loadNotReviewedItem();
});

//修改页码
function updatePage(pageNum) {
    //获取页码
    $("#pageNum").val(pageNum);
    //查询数据
    loadNotReviewedItem();
}

function loadReviewedItem() {

    var params = getReviewedParams();
    if (params) {
        var $tbody = $('#tbodyReviewedTableList');
        $tbody.empty();
        WeKnow.loading();
        $.ajax({
            type: "POST",
            url: "prescriptionAudit/reviewedList",
            dataType: "json",
            data: params,
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if (data.errcode == 0) {
                    let dataInfo = data.reviewedList;
                    if (dataInfo && dataInfo.length) {
                        let e = '';
                        $(dataInfo).each(function (idx, rowData) {
                            e += '<tr data-prescription_pic_url="' + rowData.prescriptionPicUrl + '" data-institution_id="' + rowData.institutionId + '"   >';
                            // 序号
                            e += '<td class="text-center">' + (idx + 1) + '</td>';
                            // 审核日期
                            e += '<td class="text-center">' + (rowData.auditTmStr ? rowData.auditTmStr : "-") + '</td>';
                            // 医疗机构
                            e += '<td class="text-center">' + (rowData.name ? rowData.name : "-") + '</td>';
                            // 审核结果
                            if (rowData.auditResult === 1) {
                                e += '<td class="text-center">合规</td>';
                            } else {
                                e += '<td class="text-center">违规</td>';
                            }
                            // 违规类目
                            e += '<td class="text-center">' + (rowData.title ? rowData.title : "-") + '</td>';
                            // 违规内容
                            e += '<td class="text-center">' + (rowData.msgTxt ? rowData.msgTxt : "-") + '</td>';
                            // 处方图片
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="showImgSpan">查看</span></a>';
                            e += '</td>';
                            //审核人员
                            e += '<td class="text-center">' + (rowData.auditName ? rowData.auditName : "-") + '</td>';
                            //上传人员
                            e += '<td class="text-center">' + (rowData.uploaderName ? rowData.uploaderName : "-") + '</td>';
                            //上传日期
                            e += '<td class="text-center">' + (rowData.uploadTmStr ? rowData.uploadTmStr : "-") + '</td>';
                            e += '</tr>';
                        });
                        $tbody.append(e);
                    } else {
                        WeKnow.notifyMsg('暂无数据');
                    }
                    //页码修改
                    if (allPageOther != data.pages) {
                        allPageOther = data.pages;
                        //重新生成页面下拉
                        let $selectPageOther = $('#selectPageOther');
                        $selectPageOther.empty();
                        let e = '';
                        for (let i = 1; i <= allPageOther; i++) {
                            e += '<option value="' + i + '">' + i + '</option>';
                        }
                        $selectPageOther.append(e);
                        //总页码
                        $(".allPageOther").html("共" + allPageOther + "页");
                    }
                    //限制上一页
                    if (params.pageNum == 1) {
                        $(".upPageDivOther").html('上一页');
                    } else {
                        $(".upPageDivOther").html('<a href="javascript:updatePageOther(' + (parseInt(params.pageNum) - 1) + ')">上一页</a>');
                    }
                    //限制下一页
                    if (params.pageNum >= allPageOther) {
                        $(".downPageDivOther").html('下一页');
                    } else {
                        $(".downPageDivOther").html('<a href="javascript:updatePageOther(' + (parseInt(params.pageNum) + 1) + ')">下一页</a>');
                    }
                    //修改当前页码
                    $("#selectPageOther").val(params.pageNum);
                } else if (data.errcode == -1) {
                    WeKnow.errorMsg(data.errMsg);
                } else {
                    WeKnow.systemMsg('查询失败，请重新登录后再试');
                }
            }
        });
    }
}

//页面变更
$("#selectPageOther").on('change', function (e) {
    updatePageOther($(this).val())
});
//limit变更
$("#pageSizeOther").on('change', function (e) {
    //重置页码
    $("#pageNumOther").val(1);
    //查询数据
    loadReviewedItem();
});

//修改页码
function updatePageOther(pageNum) {
    //获取页码
    $("#pageNumOther").val(pageNum);
    //查询数据
    loadReviewedItem();
}

// 收集页面查询参数
function getNotReviewedParams() {

    var data = {};

    // 标本日期 from - to
    var $dtFrom = $('#notReviewedDtFrom');
    var $dtTo = $('#notReviewedDtTo');

    if (!$dtFrom.val().length) {
        WeKnow.errorMsg('请输入查询开始日期');
        $dtFrom.focus();
        return false;
    }

    var dtFrom = $dtFrom.val();
    if (!MY_VALIDATOR.isDate(dtFrom, 'yyyy-MM-dd')) {
        WeKnow.errorMsg('查询开始日期格式不正确');
        $dtFrom.focus();
        return false;
    }
    data.dtFrom = dtFrom;

    // 查询日期to

    if (!$dtTo.val().length) {
        WeKnow.errorMsg('请输入查询结束日期');
        $dtTo.focus();
        return false;
    }

    var dtTo = $dtTo.val();
    if (!MY_VALIDATOR.isDate(dtTo, 'yyyy-MM-dd')) {
        WeKnow.errorMsg('查询结束日期格式不正确');
        $dtTo.focus();
        return false;
    }
    if ($dtFrom.val() > $dtTo.val()) {
        WeKnow.errorMsg('开始时间不能大于结束时间');
        return false;
    }
    data.dtTo = dtTo;

    // 类型
    var uploaderId = $('#uploaderId').val();
    data.uploaderId = uploaderId;
    // 表名

    var institutionName = $('#notReviewedInstitutionName').val();
    data.institutionName = institutionName;
    //页面
    data.pageNum = $("#pageNum").val();
    //一页数据加载数(limit)
    data.pageSize = $("#pageSize").val();

    return data;
}

// 收集页面查询参数
function getReviewedParams() {

    var data = {};

    // 标本日期 from - to
    var $dtFrom = $('#reviewedDtFrom');
    var $dtTo = $('#reviewedDtTo');

    if (!$dtFrom.val().length) {
        WeKnow.errorMsg('请输入查询开始日期');
        $dtFrom.focus();
        return false;
    }

    var dtFrom = $dtFrom.val();
    if (!MY_VALIDATOR.isDate(dtFrom, 'yyyy-MM-dd')) {
        WeKnow.errorMsg('查询开始日期格式不正确');
        $dtFrom.focus();
        return false;
    }
    data.dtFrom = dtFrom;

    // 查询日期to

    if (!$dtTo.val().length) {
        WeKnow.errorMsg('请输入查询结束日期');
        $dtTo.focus();
        return false;
    }

    var dtTo = $dtTo.val();
    if (!MY_VALIDATOR.isDate(dtTo, 'yyyy-MM-dd')) {
        WeKnow.errorMsg('查询结束日期格式不正确');
        $dtTo.focus();
        return false;
    }
    if ($dtFrom.val() > $dtTo.val()) {
        WeKnow.errorMsg('开始时间不能大于结束时间');
        return false;
    }
    data.dtTo = dtTo;


    var auditId = $('#auditId').val();
    data.auditId = auditId;

    var auditResult = $('#auditResult').val();
    data.auditResult = auditResult;

    var institutionName = $('#reviewedInstitutionName').val();
    data.institutionName = institutionName;

    //页面
    data.pageNum = $("#pageNumOther").val();
    //一页数据加载数(limit)
    data.pageSize = $("#pageSizeOther").val();
    return data;
}

//查看图片
$("#tbodyNotReviewedTableList,#tbodyReviewedTableList").on('click', '.showImgSpan', function (e) {
    //获取数据
    let $parentTr = $(this).closest('tr');
    MY_SHOW_IMG.showImg($parentTr.data('prescription_pic_url'), 0);
});


//打开审核界面
$("#tbodyNotReviewedTableList").on('click', '.showAuditImgSpan', function (e) {
    $('#auditPrescriptionLink').modal('show');
    //获取数据
    let $parentTr = $(this).closest('tr');
    medicalId = $parentTr.data('medical_id');
    prescriptionId = $parentTr.data('prescription_id')
    institutionId = $parentTr.data('institution_id')
});


//删除
$("#tbodyNotReviewedTableList").on('click', '.deleteSpan', function (e) {
    //获取数据
    let $parentTr = $(this).closest('tr');
    //确认框
    WeKnow.confirm("确认删除吗？", function () {
        let data = {};
        data.reviewedId = $parentTr.data('reviewed_id');
        WeKnow.loading();
        $.ajax({
            type: "POST",
            url: "prescriptionAudit/deleteAuditPrescription",
            dataType: "json",
            data: data,
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if (data.errCode == 1) {
                    window.location.reload();
                } else if (data.errCode == 0) {
                    WeKnow.errorMsg(data.errMsg);
                } else {
                    WeKnow.systemMsg('删除失败，请重新登录后再试');
                }
            }
        });
    });
});